package ran.quzitech.rnutils.manager;

import android.content.Context;
import android.text.TextUtils;
import android.util.Base64;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2016/12/2 0002.
 */
public class AssetsManager extends ReactContextBaseJavaModule {

    private Context context;
    private ReactContext reactContext;

    private static final String LOG_TAG = "custom_AssetsManager";


    @Override
    public String getName() {
        return "AssetsManager";
    }

    public AssetsManager(ReactApplicationContext reactContext) {
        super(reactContext);
        context = reactContext;
        this.reactContext = reactContext;


    }


    private Map<String, String> configCache = new HashMap<>();
    private final static String ASSET_PATH = "latticeConfig/";

    /**
     * 提供给RN调用读取配置的方法
     * pageName= 页面名
     */
    @ReactMethod
    public void getConfig(String pageName, Callback callback) {

        String config = configCache.get(pageName);
        Context context = getReactApplicationContext();

        if (TextUtils.isEmpty(config)) {
            config = ReadFromAsset(context, pageName);
        }
        callback.invoke(null, config);
        //返回给RN处
//        promise.resolve(ReactArguments.toWritableMap(config));
//        configCache.put(pageName, config);

    }

    /**
     * 读取assts下的* latticeConfig/LatticeMockModule.json文件
     **/
    private String ReadFromAsset(Context context, String pageName) {
        try {
            InputStream in = context.getAssets().open(ASSET_PATH + pageName + ".proto");
            BufferedReader bf = new BufferedReader(new InputStreamReader(in));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = bf.readLine()) != null) {
                sb.append(line +"   "+"\n\t");
            }
            line = sb.toString();
            return line;


        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
